Go Get Path To Current File (Example) | 您所在的位置:网站首页 › go to file › Go Get Path To Current File (Example) |
I recently needed to get the current file absolute path from a go file. You first need to get the runtime package which is a part of Go import "runtime"Next you can use the Caller method and capture the filename. We need to give this function a 1 to tell it to skip up a caller. You can read more about the function here _, filename, _, ok := runtime.Caller(1)The filename will be the path up to the current directory of the file that calls this function. The ok is to check if the function call was able to find the information requested. So in practice if you wanted to get a config file up a directory and in a config directory you could do the following filepath := path.Join(path.Dir(filename), "../config/settings.toml") |
CopyRight 2018-2019 实验室设备网 版权所有 |